import { createRouter, createWebHistory } from "vue-router";
import store from '@/store';
//导入进度条插件
import useNprogress from '@/hooks/useNProgress';
const NProgress=useNprogress();

// routes节点中初始化只加载不重要的路由,对于有权限的路由应该在用户登录之后进行统一加载和管理
const routes = [
  {
    path: "/",
    name:'layout',
    component: () =>
      import(/* webpackChunkName: "layout" */ "@/layout/index.vue"),
    children:[]
  },
  {
    path: "/home",
    name: "home",
    component: () =>
      import(/* webpackChunkName: "layout" */ "@/layout/index.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    name: "ErrorPage",
    component: () =>
      import(/* webpackChunkName: "NotFoundPage" */ "../views/NotFoundPage.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

//设置路由导航守卫
router.beforeEach((to,from,next)=>{
  NProgress.start();
  const tokenStr=store.state.userStore.token;
  if(to.path!=='/login'){
    if(!tokenStr){
      next('/login'); 
    }else{
      //如果用户只是刷新了界面,页面跳转到用户想去的路由即可
      if (!store.state.userStore.isDynamicAddedRoute) {
        store.dispatch("loadAsyncRoute").then(() => {
          router.push(to.fullPath);
        });
      } else {
        next();
      }
    }  
  }else{
    next();
  }
})

//路由后置守卫
router.afterEach((to,from,next)=>{
  NProgress.done();
})

export default router;
